package com.companyName.common.redis;

import java.util.Set;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisPoolFactory extends AbsJedisFactory implements FactoryBean<JedisPool> ,InitializingBean{
	@Autowired
	private RedisConfig redisConfig;
	
	/**
	 * Jedis连接池
	 */
	private JedisPool jedisPool;

	@Override
	public JedisPool getObject() throws Exception {
		return jedisPool;
	}

	@Override
	public Class<?> getObjectType() {
		return (this.jedisPool != null ? this.jedisPool.getClass() : JedisPool.class);
	}

	@Override
	public boolean isSingleton() {
		return true;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		if(!redisConfig.isCluster()){
			Set<HostAndPort> hostAndPortSet = parseHostAndPort(redisConfig.getAddress());
			JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();

			jedisPoolConfig.setMaxWaitMillis(redisConfig.getMaxWaitMillis());
			jedisPoolConfig.setMaxTotal(redisConfig.getMaxTotal());
			jedisPoolConfig.setMinIdle(redisConfig.getMinIdle());
			jedisPoolConfig.setMaxIdle(redisConfig.getMaxIdle());
			
			for (HostAndPort hostAndPort : hostAndPortSet) {
				jedisPool = new JedisPool(jedisPoolConfig, hostAndPort.getHost(), hostAndPort.getPort(), redisConfig.getTimeout());
			}
		}		
	}
	

	public void setRedisConfig(RedisConfig redisConfig) {
		this.redisConfig = redisConfig;
	}

}
